# before doing this question, please make sure you clarify  'w', 'r', 'a' in open functino.
# Please implement a Class MyCSV to implement
#  1. load: load a csv if exists, otherwise, create a empty csv file
#  2. insert(row_number, content): insert a new row in the row_number by content
#  3. delete(row_number): delete a row number
#  4. show(row_number): show the content of row number
# Plus: I have a txt file with 100000000 lines, which is greater than your memory can read
# Define a function  def txt2csv(start, end) to read lines from start to end and insert to a csv


import csv
import os

from generateText import TextGenerator


class RowNumberOutOfRangeException(Exception):
    pass


class MyCSV:

    def __init__(self, filename):
        self.rows = None
        self.filename = filename

    # 尝试加载csv文件,如果不存在则创建
    def load(self):
        try:
            self.rows = []
            with open(self.filename, 'r', newline='', encoding="utf-8") as f:
                reader = csv.reader(f)
                for row in reader:
                    self.rows.append(row)
        except FileNotFoundError:
            with open(self.filename, 'w', newline='', encoding="utf-8") as f:
                pass

    # 从内存中插入数据，并调用write_file方法覆盖写入内容到 csv
    def insert(self, row_number, content):
        if row_number < len(self.rows):
            del self.rows[row_number]
        self.rows.insert(row_number, [content])
        self.write_file()

    # 从内存中删除数据，并调用write_file方法覆盖写入内容到 csv
    # 为了确保没有索引溢出，增加自定义异常RowNumberOutOfRangeError判断行号是否超出范围
    def delete(self, row_number):
        if row_number >= len(self.rows):
            raise RowNumberOutOfRangeException("Row number out of range")

        del self.rows[row_number]
        self.write_file()

    # 显示行号
    def show(self, row_number):
        print(self.rows[row_number])

    # 覆盖写入内容到 csv
    def write_file(self):
        with open(self.filename, 'w', newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerows(self.rows)


# 通过迭代只读取指定行到CSV中,不会全部加载到内存
def txt2csv(txt_file, csv_file, start, end):
    with open(txt_file) as tf, open(csv_file, 'a') as cf:
        writer = csv.writer(cf)
        for i, line in enumerate(tf):
            if start <= i < end:
                writer.writerow([line])


if __name__ == "__main__":
    txt_filename = 'a.txt'
    csv_filename = 'a.csv'
    csv_file = MyCSV(csv_filename)

    csv_file.load()

    for i in range(0, 99):
        csv_file.insert(i, "frank")
        csv_file.write_file()
        csv_file.show(i)

    for i in range(0, 99):
        csv_file.insert(i, "charlie")
        csv_file.write_file()
        csv_file.show(i)

    # for i in range(0, 99):
    #     csv_file.delete(0)
    #
    # if os.path.exists(csv_file.filename):
    #     os.remove(csv_file.filename)

    text_gen = TextGenerator()
    text_gen.generate(txt_filename, 100000000, 'xxx')
    txt2csv(txt_filename, "b.csv", 0, 1000)
